package org.zj.webview;

import java.io.*;
import java.nio.file.*;

/**
 * @author zj
 * @since 2025/6/29
 */
public class WebViewInstallUtils {

    private static final String VERSION = "1.0.0.1";

    private WebViewInstallUtils() {
    }

    /**
     * 更新组件
     *
     * @return
     */
    public static synchronized void install() throws IOException {
        String libraryPath = System.getProperty("webview2.library.path");
        if (libraryPath == null || libraryPath.isEmpty()) {
            libraryPath = "bin";
        }
        final String main = "JWebView2.dll";
        final String binder = "JWebView2.JavaBinder.dll";
        final String arch = "/webview2/" + System.getProperty("os.arch") + "/";
        final File binDir = new File(libraryPath, arch + VERSION);
        final File binderDll = new File(binDir, binder);
        final File mainDll = new File(binDir, main);

        update(arch + main, mainDll);
        update(arch + binder, binderDll);

        System.load(mainDll.getAbsolutePath());
        System.load(binderDll.getAbsolutePath());
    }


    /**
     * 更新文件
     *
     * @throws IOException
     */
    private static void update(String resourcePath, File exe) throws IOException {
        File parentFile = exe.getParentFile();
        if (!parentFile.exists()) {
            Files.createDirectories(parentFile.toPath());
        }
        if (exe.exists() && exe.length() > 0) {
            return;
        }
        Path tempFile = Files.createTempFile(parentFile.toPath(), "", ".tmp");
        try (OutputStream outputStream = new BufferedOutputStream(
                Files.newOutputStream(tempFile, StandardOpenOption.TRUNCATE_EXISTING));
             InputStream inputStream = WebViewInstallUtils.class.getResourceAsStream(resourcePath)) {
            assert inputStream != null;
            transferTo(inputStream, outputStream);
        }
        Files.move(tempFile, Paths.get(exe.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
    }

    /**
     * 输入流转输出流
     * @param inputStream
     * @param outputStream
     * @throws IOException
     */
    private static void transferTo(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[8192];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
    }
}
